package com.winsomely.leecode;

import java.util.HashMap;
import java.util.Map;

/**
 * 区域和检索 - 数组不可变
 * 
 * @author liujiawei
 *
 */
public class NumArray {

	private int[] nums;

	private Map<String, Integer> map = new HashMap<>();

	private int ci = Integer.MIN_VALUE;
	private int cj = Integer.MAX_VALUE;

	public NumArray(int[] nums) {
		this.nums = nums;
	}

	public int sumRange(int i, int j) {
		int ti = i;
		int tj = j;
		Integer cacheSum = map.get(i + "_" + j);
		if (cacheSum != null) {
			return cacheSum;
		}

		int sum = 0;
		if (i <= ci && j >= cj) {
			sum = map.get(ci + "_" + cj);
			for (; i < ci; i++) {
				sum += nums[i];
			}
			for (; j > cj; j--) {
				sum += nums[j];
			}
		} else {
			for (; i <= j; i++) {
				sum += nums[i];
			}
		}
		ci = ti;
		cj = tj;
		map.put(ci + "_" + cj, sum);
		return sum;
	}

	public static void main(String[] args) {
		System.out.println(Integer.MIN_VALUE);
		int[] nums = { 1, 2, 3, 4, 5, 6 };
		int i = 0;
		int j = 3;
		NumArray t = new NumArray(nums);
		System.out.println(t.sumRange(i, j));
		i = 1;
		j = 4;
		System.out.println(t.sumRange(i, j));
		System.out.println(t.sumRange(i, j));
		i = 0;
		j = 5;
		System.out.println(t.sumRange(i, j));
		
		
	}

}
